package com.kexio.sms.impl;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import com.kexio.common.dto.Result;
import com.kexio.sms.config.SmsProperties;
import com.kexio.sms.entity.SmsRecord;
import com.kexio.sms.entity.SmsTemplate;
import com.kexio.sms.enums.SmsStatus;
import com.kexio.sms.service.SmsService;
import com.kexio.sms.service.SmsTemplateService;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;

/**
 * 短信服务实现
 * 
 * @author Kexio Team
 * @since 1.0.0
 */
@Service
@ConditionalOnProperty(prefix = "kexio.sms", name = "enabled", havingValue = "true")
public class SmsServiceImpl implements SmsService {
    
    private static final Logger logger = LoggerFactory.getLogger(SmsServiceImpl.class);
    
    @Autowired
    private SmsProperties smsProperties;
    
    @Autowired(required = false)
    private SmsTemplateService templateService;
    
    // 模拟存储 (实际应该注入Mapper)
    private final Map<String, SmsRecord> recordStorage = new HashMap<>();
    
    @Override
    public Result<SmsRecord> sendSms(String phone, String content, String smsType) {
        logger.info("发送短信: phone={}, type={}, content length={}", phone, smsType, content.length());
        
        try {
            // 参数验证
            if (StrUtil.isBlank(phone) || StrUtil.isBlank(content)) {
                return Result.error("手机号和短信内容不能为空");
            }
            
            // 手机号格式验证
            if (!isValidPhone(phone)) {
                return Result.error("手机号格式不正确");
            }
            
            // 创建发送记录
            SmsRecord record = new SmsRecord(phone, content, smsType, smsProperties.getDefaultProvider());
            record.setId(IdUtil.fastSimpleUUID());
            record.setSendTime(LocalDateTime.now());
            
            // 调用实际发送逻辑 (这里模拟)
            boolean sendResult = doSendSms(record);
            
            if (sendResult) {
                record.setStatus(SmsStatus.SUCCESS.getCode());
                record.setMessageId("MSG_" + System.currentTimeMillis());
                record.setDuration(100L); // 模拟发送耗时
            } else {
                record.setStatus(SmsStatus.FAILED.getCode());
                record.setErrorCode("SEND_FAILED");
                record.setErrorMessage("发送失败");
            }
            
            // 保存记录
            recordStorage.put(record.getId(), record);
            
            return Result.success(sendResult ? "发送成功" : "发送失败", record);
            
        } catch (Exception e) {
            logger.error("发送短信异常", e);
            return Result.error("发送短信异常: " + e.getMessage());
        }
    }
    
    @Override
    public Result<SmsRecord> sendSms(String phone, String templateCode, Map<String, Object> templateParams, String smsType) {
        logger.info("发送模板短信: phone={}, templateCode={}, type={}", phone, templateCode, smsType);
        
        try {
            // 参数验证
            if (StrUtil.isBlank(phone) || StrUtil.isBlank(templateCode)) {
                return Result.error("手机号和模板编码不能为空");
            }
            
            // 获取模板
            SmsTemplate template = null;
            if (templateService != null) {
                template = templateService.getTemplateByCode(templateCode);
                if (template == null) {
                    return Result.error("短信模板不存在: " + templateCode);
                }
            }
            
            // 渲染模板内容
            String content;
            if (template != null && templateService != null) {
                Result<String> renderResult = templateService.renderTemplate(templateCode, templateParams);
                if (!renderResult.isSuccess()) {
                    return Result.error("模板渲染失败: " + renderResult.getMessage());
                }
                content = renderResult.getData();
            } else {
                // 简单的参数替换 (实际应该使用模板引擎)
                content = "模板消息: " + templateCode;
            }
            
            // 创建发送记录
            SmsRecord record = new SmsRecord(phone, content, smsType, smsProperties.getDefaultProvider());
            record.setId(IdUtil.fastSimpleUUID());
            record.setTemplateId(templateCode);
            record.setTemplateParams(templateParams != null ? templateParams.toString() : null);
            record.setSendTime(LocalDateTime.now());
            
            // 发送短信
            boolean sendResult = doSendSms(record);
            
            if (sendResult) {
                record.setStatus(SmsStatus.SUCCESS.getCode());
                record.setMessageId("MSG_" + System.currentTimeMillis());
                record.setDuration(120L);
                
                // 增加模板使用次数
                if (templateService != null) {
                    templateService.incrementUsageCount(templateCode);
                }
            } else {
                record.setStatus(SmsStatus.FAILED.getCode());
                record.setErrorCode("TEMPLATE_SEND_FAILED");
                record.setErrorMessage("模板短信发送失败");
            }
            
            // 保存记录
            recordStorage.put(record.getId(), record);
            
            return Result.success(sendResult ? "发送成功" : "发送失败", record);
            
        } catch (Exception e) {
            logger.error("发送模板短信异常", e);
            return Result.error("发送模板短信异常: " + e.getMessage());
        }
    }
    
    @Override
    public Result<String> batchSendSms(String[] phones, String content, String smsType) {
        logger.info("批量发送短信: phones.length={}, type={}", phones.length, smsType);
        
        try {
            if (phones == null || phones.length == 0) {
                return Result.error("手机号列表不能为空");
            }
            
            int successCount = 0;
            int failedCount = 0;
            
            for (String phone : phones) {
                Result<SmsRecord> result = sendSms(phone, content, smsType);
                if (result.isSuccess()) {
                    successCount++;
                } else {
                    failedCount++;
                }
            }
            
            String message = String.format("批量发送完成: 成功%d条, 失败%d条", successCount, failedCount);
            return Result.success(message, "BATCH_" + System.currentTimeMillis());
            
        } catch (Exception e) {
            logger.error("批量发送短信异常", e);
            return Result.error("批量发送短信异常: " + e.getMessage());
        }
    }
    
    @Override
    public Result<String> batchSendSms(String[] phones, String templateCode, Map<String, Object> templateParams, String smsType) {
        logger.info("批量发送模板短信: phones.length={}, templateCode={}, type={}", phones.length, templateCode, smsType);
        
        try {
            if (phones == null || phones.length == 0) {
                return Result.error("手机号列表不能为空");
            }
            
            int successCount = 0;
            int failedCount = 0;
            
            for (String phone : phones) {
                Result<SmsRecord> result = sendSms(phone, templateCode, templateParams, smsType);
                if (result.isSuccess()) {
                    successCount++;
                } else {
                    failedCount++;
                }
            }
            
            String message = String.format("批量发送完成: 成功%d条, 失败%d条", successCount, failedCount);
            return Result.success(message, "BATCH_" + System.currentTimeMillis());
            
        } catch (Exception e) {
            logger.error("批量发送模板短信异常", e);
            return Result.error("批量发送模板短信异常: " + e.getMessage());
        }
    }
    
    @Override
    public SmsRecord getRecord(String recordId) {
        return recordStorage.get(recordId);
    }
    
    @Override
    public String getStatus(String recordId) {
        SmsRecord record = recordStorage.get(recordId);
        return record != null ? record.getStatus() : null;
    }
    
    @Override
    public boolean isProviderSupported(String provider) {
        return "aliyun".equals(provider) || "tencent".equals(provider) || "huawei".equals(provider);
    }
    
    @Override
    public String getCurrentProvider() {
        return smsProperties.getDefaultProvider();
    }
    
    @Override
    public Result<String> switchProvider(String provider) {
        if (!isProviderSupported(provider)) {
            return Result.error("不支持的服务提供商: " + provider);
        }
        
        logger.info("切换短信服务提供商: {} -> {}", smsProperties.getDefaultProvider(), provider);
        
        // 这里应该动态更新配置，这里仅做演示
        smsProperties.setDefaultProvider(provider);
        
        return Result.success("服务提供商切换成功", provider);
    }
    
    @Override
    public Map<String, Object> getStatistics(String timeRange) {
        Map<String, Object> stats = new HashMap<>();
        
        // 模拟统计数据
        stats.put("totalSent", recordStorage.size());
        stats.put("successCount", recordStorage.values().stream()
            .mapToLong(r -> SmsStatus.SUCCESS.getCode().equals(r.getStatus()) ? 1 : 0)
            .sum());
        stats.put("failedCount", recordStorage.values().stream()
            .mapToLong(r -> SmsStatus.FAILED.getCode().equals(r.getStatus()) ? 1 : 0)
            .sum());
        stats.put("timeRange", timeRange);
        
        return stats;
    }
    
    /**
     * 实际发送短信逻辑 (模拟实现)
     */
    private boolean doSendSms(SmsRecord record) {
        try {
            String provider = record.getProvider();
            
            // 根据服务提供商调用对应的SDK
            switch (provider) {
                case "aliyun":
                    return sendByAliyun(record);
                case "tencent":
                    return sendByTencent(record);
                case "huawei":
                    return sendByHuawei(record);
                default:
                    logger.warn("不支持的服务提供商: {}", provider);
                    return false;
            }
            
        } catch (Exception e) {
            logger.error("发送短信失败", e);
            record.setErrorCode("PROVIDER_ERROR");
            record.setErrorMessage(e.getMessage());
            return false;
        }
    }
    
    /**
     * 阿里云短信发送 (模拟实现)
     */
    private boolean sendByAliyun(SmsRecord record) {
        logger.debug("使用阿里云发送短信: {}", record.getPhone());
        // 这里应该调用阿里云SMS SDK
        // 模拟发送成功
        return Math.random() > 0.1; // 90% 成功率
    }
    
    /**
     * 腾讯云短信发送 (模拟实现)
     */
    private boolean sendByTencent(SmsRecord record) {
        logger.debug("使用腾讯云发送短信: {}", record.getPhone());
        // 这里应该调用腾讯云SMS SDK
        // 模拟发送成功
        return Math.random() > 0.1; // 90% 成功率
    }
    
    /**
     * 华为云短信发送 (模拟实现)
     */
    private boolean sendByHuawei(SmsRecord record) {
        logger.debug("使用华为云发送短信: {}", record.getPhone());
        // 这里应该调用华为云SMS SDK
        // 模拟发送成功
        return Math.random() > 0.1; // 90% 成功率
    }
    
    /**
     * 验证手机号格式
     */
    private boolean isValidPhone(String phone) {
        if (StrUtil.isBlank(phone)) {
            return false;
        }
        // 简单的手机号验证 (11位数字)
        return phone.matches("^1[3-9]\\d{9}$");
    }
}
